def analyze_data():
    global displacements, voltages

    # 弹出文件选择对话框
    file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx;*.xls")])

    if file_path:
        # 读取Excel数据
        df = pd.read_excel(file_path, header=None)
        displacements = df.iloc[0].values  # 位移 (mm)
        voltages = df.iloc[1].values  # 电压 (mV)

        # 计算拟合直线的斜率
        coefficients = np.polyfit(displacements, voltages, 1)
        slope = coefficients[0]

        # 计算灵敏度
        sensitivity = slope

        # 计算非线性误差
        deviations = np.abs(voltages - (slope * displacements))
        delta_m = np.max(deviations)
        nonlinearity_error = (delta_m / voltages[-1]) * 100

        # 绘制位移-电压曲线
        plt.plot(displacements, voltages, 'ro', label='实验数据')
        plt.xlabel('重量 (g)')
        plt.ylabel('电压 (mV)')

        # 绘制拟合直线
        fit_line_values = slope * displacements
        plt.plot(displacements, fit_line_values, 'b-', label='拟合直线')

        # 在图上标注数字点位
        for i, (d, v) in enumerate(zip(displacements, voltages)):
            plt.text(d, v, f'({d}, {v})', fontsize=8, verticalalignment='center', horizontalalignment='left')

        # 显示结果
        result_window = tk.Toplevel(root)
        result_window.title("数据分析结果")

        # 构建计算过程的文本
        process_text = f"数据分析步骤：\n" \
                       f"1. 计算拟合直线的斜率:\n" \
                       f"   斜率 = {slope}\n" \
                       f"2. 计算灵敏度\n" \
                       f"   灵敏度 (S) = 拟合直线斜率 = {sensitivity}\n" \
                       f"3. 计算非线性误差\n" \
                       f"   Δm = max(|电压 - 拟合直线的电压|) = {delta_m}\n" \
                       f"   yFS = {voltages[-1]}\n" \
                       f"   非线性误差 = (Δm / yFS) * 100%\n" \
                       f"             = ({delta_m} / {voltages[-1]}) * 100%\n" \
                       f"             ≈ {nonlinearity_error}%"

        # 创建一个滚动条
        scrollbar = tk.Scrollbar(result_window, orient=tk.VERTICAL)

        # 创建一个Text来显示文本
        result_text = tk.Text(result_window, wrap=tk.WORD)
        result_text.insert(tk.END, process_text)

        # 配置滚动条和Text
        scrollbar.config(command=result_text.yview)
        result_text.config(yscrollcommand=scrollbar.set)

        # 显示Text和滚动条
        result_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        # 显示位移-电压曲线
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        plt.legend()
        plt.show()

root = tk.Tk()
root.title("数据分析应用")
root.geometry("300x200")

# 创建按钮
analyze_button = tk.Button(root, text="开始数据分析", command=analyze_data)
analyze_button.pack()

# 启动主循环
root.mainloop()
